﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Sellers;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class SellerEmployeeController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        #region 获取员工详情  ActionResult Detail(int id)
        /// <summary>
        /// 获取员工详情
        /// </summary>
        /// <returns></returns>
        public ActionResult Detail(int id)
        {
            var sellerEmployee = ServiceFactory.SellerEmployeeServiceInstance.LoadByID(id);
            return View(sellerEmployee);
        }
        #endregion
        #region 获取员工列表  JsonResult Index(SellerEmployeeModel model)
        [HttpPost]
        public JsonResult Index(SellerEmployeeModel model)
        {
            var total = 0;
            var list = ServiceFactory.SellerEmployeeServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.UserName,
                o.UserAccount,
                o.Email,
                o.CertificateNO,
                o.UserPhone,
                o.Sellers.SellersName,
                o.IsAvailable,
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd hh:mm:ss")
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
#endregion 
        #region 
        [HttpPost]
        public JsonResult GetSellerEmployeeInfo(int id = 0)
        {
            var result = ServiceFactory.SellerEmployeeServiceInstance.LoadEntities(m => m.ID == id).Select(o => new
            {
                o.ID,
                o.IsAvailable,
                o.UserAccount,
                o.UserName,
                o.SellerId,
                o.UserPhone,
                o.CertificateNO,
                o.Email
            }).FirstOrDefault();
            return result == null ? Json(new { success = false, message = "员工不存在" }) : Json(new { success = true, result });
        }
#endregion
        #region 保存员工信息   ActionResult UpdateSellerEmployeeForm(SellerEmployee model, int Type = 0)
        [HttpPost]
        public ActionResult UpdateSellerEmployeeForm(SellerEmployee model, int Type = 0)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Update
            };
            var serv = ServiceFactory.SellerEmployeeServiceInstance;
            if (model.ID > 0)
            {
                var entity = serv.LoadByID(model.ID);
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.UserAccount = model.UserAccount;
                entity.UserPhone = model.UserPhone;
                entity.UserName = model.UserName;
                entity.CertificateNO = model.CertificateNO;
                entity.Email = model.Email;
                entity.IsAvailable = model.IsAvailable;
                if (serv.UpdateEntities(entity))
                {
                    responseResult.Success = true;
                    responseResult.Message = "更新成功！";
                    TempData["ResponseResult"] = responseResult;
                    return Type == 1
                        ? Content("<script>window.location.href = '/SellerEmployee/';</script>")
                        : Content("<script>window.close();parent.location.href = parent.location.href;</script>");
                }
            }
            else
            {
                if (serv.IsExist(model.UserAccount, model.UserName))
                {
                    responseResult.Success = true;
                    responseResult.Message = "销售商员工账号或名称已存在";
                    TempData["ResponseResult"] = responseResult;
                    return Content("<script>window.location.href = '/SellerEmployee/';</script>");
                }
                if (Type == 1)
                {
                    var order = ServiceFactory.SellersServiceInstance.LoadByID(model.SellerId);
                    if (order != null)
                    {
                        var servorgan = ServiceFactory.SellersOrganizationServiceInstance;
                        var entity1 = servorgan.LoadByID(order.SellersOrganizationId);
                        model.InsuranceCompanyBranch = entity1.OrganizationName;
                        model.InsuranceCompany = servorgan.LoadParentOrganization(
                            entity1.ParentOrganizationId).OrganizationName;
                    }
                }
                model.CreateTime = DateTime.Now;
                model.CreateBy = CurrentUser.UserAccount;
                model.LastModifyTime = DateTime.Now;
                model.LastModifyBy = CurrentUser.UserAccount;
                model.Password = CommonMethod.JiaMi(model.Password);
                var entity = serv.AddEntities(model);
                responseResult.Success = entity.ID > 0;
                responseResult.Message =  entity.ID > 0?"添加成功！":"添加失败！";
            }
            TempData["ResponseResult"] = responseResult;
            return Type == 1
                ? Content("<script>window.location.href = '/SellerEmployee/';</script>") : Content("<script>window.close();parent.location.href = parent.location.href;</script>");
        }
#endregion
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="newPassWord">新密码</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RestPassWord(int id, string newPassWord)
        {
            var result = ServiceFactory.SellerEmployeeServiceInstance.LoadEntities(p => p.ID == id).FirstOrDefault();
            if (result != null)
            {
                result.Password = CommonMethod.JiaMi(newPassWord);
                return Json(ServiceFactory.SellerEmployeeServiceInstance.UpdateEntities(result) ? new { success = true, message = "重置用户密码成功" } : new { success = false, message = "重置用户密码失败" });
            }
            else
            {
                return Json(new { success = false, message = "找不到该用户" });
            }
        }
        #region 修改员工状态 JsonResult UpdateSellerEmployee(int id, bool isAvailable)
        [HttpPost]
        public JsonResult UpdateSellerEmployee(int id, bool isAvailable)
        {
            SellerEmployee entity = ServiceFactory.SellerEmployeeServiceInstance.LoadByID(id);
            bool success = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                success = ServiceFactory.SellerEmployeeServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion
        public ActionResult SellerEmployeeRoleMapping()
        {
            var model = ServiceFactory.SellerEmployeeRoleServiceInstance.LoadAll().ToList();
            return View(model);
        }
        #region 设置员工
        [HttpPost]
        public ContentResult SaveSellerEmployeeRoleMapping(SellerEmployeeRoleMapping model)
        {
            var result = false;
            if (model != null && model.SellerEmployeeID > 0)
            {
                var sellerEmployeeRoleIDs = Request["SellerEmployeeRoleID"];
                if (!string.IsNullOrEmpty(sellerEmployeeRoleIDs))
                {
                    var longSellerEmployeeRoleIDs = sellerEmployeeRoleIDs.Split(',').ToList().ConvertAll(long.Parse);
                    for (int i = 0; i < longSellerEmployeeRoleIDs.Count; i++)
                    {
                        result = ServiceFactory.SellerEmployeeRoleMappingServiceInstance.AddSellerEmployeeRoleMappings(
                            model.SellerEmployeeID, longSellerEmployeeRoleIDs);
                    }
                }
                else
                {
                    result = ServiceFactory.SellerEmployeeRoleMappingServiceInstance.DeleteSellerEmployeeRoleMappings(
                            model.SellerEmployeeID);
                }

            }
            return Content(string.Format("<script>alert('{0}！');parent.layer.closeAll();</script>", result ? "设置成功！" : "设置失败！"));
        }
    }
        #endregion
}